package co.edu.uniandes.moviles.rollerjudge;

import java.util.ArrayList;
import java.util.List;

import net.sourceforge.zbar.Symbol;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import co.edu.uniandes.moviles.rollerjudge.logica.Equipo;
import co.edu.uniandes.moviles.rollerjudge.logica.RollerJudge;

import com.dm.zbar.android.scanner.ZBarConstants;
import com.dm.zbar.android.scanner.ZBarScannerActivity;

public class CrearParticipanteActivity extends Activity{
	

	private static final int ZBAR_SCANNER_REQUEST = 0;
	private static final int ZBAR_QR_SCANNER_REQUEST = 1;

	protected static final int DATE_DIALOG_ID = 999;
	private String nombre;
	private String genero;
	private String email;
	private int numero;
	private int edad;
	private String docIdentidad;
	private Spinner spinner1, spinner2;
	private Button btnSummit;
	private String grupo;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		RollerJudge roller = RollerJudge.darInstancia();
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_crear_patinador);
		
		spinner1 = (Spinner) findViewById(R.id.spinner1);
		List<String> list2 = new ArrayList<String>();
		list2.add("Hombre");
		list2.add("Mujer");
		ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this,
			android.R.layout.simple_spinner_item, list2);
		dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner1.setAdapter(dataAdapter2);
		
		spinner2 = (Spinner) findViewById(R.id.spinner2);
		List<String> list = new ArrayList<String>();
		for(int i=0;i<roller.darEquipos().size();i++)
		{
			Equipo eq= roller.darEquipos().get(i);
			list.add(eq.getNombre());
			
		}
		
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
			android.R.layout.simple_spinner_item, list);
		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner2.setAdapter(dataAdapter);
		

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	public void launchQRScanner(View v) {
		if (isCameraAvailable()) {
			Intent intent = new Intent(this, ZBarScannerActivity.class);
			intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{Symbol.QRCODE});
			startActivityForResult(intent, ZBAR_SCANNER_REQUEST);
		} else {
			Toast.makeText(this, "Rear Facing Camera Unavailable", Toast.LENGTH_SHORT).show();
		}
	}

	public boolean isCameraAvailable() {
		PackageManager pm = getPackageManager();
		return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA);
	}


	@SuppressWarnings("deprecation")
	public void showDialog(String title, String message, final boolean finishAfterClose) {
		AlertDialog alertDialog = new AlertDialog.Builder(this).create();
		alertDialog.setTitle(title);
		alertDialog.setMessage(message);
		alertDialog.setButton("Aceptar", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(final DialogInterface dialog, final int which) {				
				if(finishAfterClose){
					finish();
				}
			}
		});
		alertDialog.show();
	}

	public void crearPatinador(View view){
		EditText txtNombre = (EditText)findViewById(R.id.editTxtNombre);
		nombre = txtNombre.getText().toString();

		EditText txtDoc = (EditText)findViewById(R.id.editDocIden);
		docIdentidad = txtDoc.getText().toString();

		EditText txtEdad = (EditText)findViewById(R.id.editEdad);
		edad = Integer.parseInt(txtEdad.getText().toString());
		
		EditText txtEmail = (EditText)findViewById(R.id.txtEmail);
		email = txtEmail.getText().toString();
		
		EditText txtNum = (EditText)findViewById(R.id.txtNum);
		numero = Integer.parseInt(txtNum.getText().toString());
		
		
		spinner1 = (Spinner) findViewById(R.id.spinner1);
		spinner2 = (Spinner) findViewById(R.id.spinner2);
		
		genero = String.valueOf(spinner1.getSelectedItem());
		grupo = String.valueOf(spinner2.getSelectedItem());
		
		try {
			
			System.out.println("nombre:" + nombre +" edad:" + edad +" cc:" + docIdentidad+ " genero: "+genero+"grupo: "+grupo);
			RollerJudge.darInstancia().registrarPatinador(nombre, docIdentidad, numero, email, edad, genero, grupo);
			finish();

		} catch(Exception e) {
			if(e.getMessage().equals("Ya existe un patinador con ese documento."))
				showDialog("Patinador Duplicado", e.getMessage(), false);
		}	

	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case ZBAR_SCANNER_REQUEST:
		case ZBAR_QR_SCANNER_REQUEST:
			if (resultCode == RESULT_OK) {
				String res = data.getStringExtra(ZBarConstants.SCAN_RESULT);
				String[] datos = res.split(";");
				nombre = datos[0];
				docIdentidad = datos[1];
				numero = Integer.parseInt(datos[2]);
				email = datos[3];
				edad = Integer.parseInt(datos[4]);
				genero = datos[5];
				grupo = datos[6];
				try {
					
					System.out.println("Registrado - nombre:" + nombre +" edad:" + edad +" cc:" + docIdentidad+ " genero: "+genero+"grupo: "+grupo);
					RollerJudge.darInstancia().registrarPatinador(nombre, docIdentidad, numero, email, edad, genero, grupo);
					finish();
					Toast.makeText(this, "Registrado - nombre:" + nombre +" edad:" + edad +" cc:" + docIdentidad+ " genero: "+genero+"grupo: "+grupo, Toast.LENGTH_SHORT).show();

				} catch(Exception e) {
					if(e.getMessage().equals("Ya existe un patinador con ese documento."))
						showDialog("Patinador Duplicado", e.getMessage(), false);
				}	
//				Toast.makeText(this, "Scan Result = " + data.getStringExtra(ZBarConstants.SCAN_RESULT), Toast.LENGTH_SHORT).show();
			} else if(resultCode == RESULT_CANCELED && data != null) {
				String error = data.getStringExtra(ZBarConstants.ERROR_INFO);
				if(!TextUtils.isEmpty(error)) {
					Toast.makeText(this, error, Toast.LENGTH_LONG).show();
				}
			}
			break;
		}
	}

}


